<?php

namespace Gnway\Ticket\Rest\Annotation\Parser;

use Gnway\Ticket\Rest\Annotation\Controller;
use Gnway\Ticket\Rest\Container\RestContainer;
use Gnway\Ticket\Rest\Util\FileUtils;
use ReflectionException;
use stdClass;

/**
 * Class ControllerParser
 */
class ControllerParser extends AbstractParser
{

  /**
   * Controller Files
   *
   * @var array
   */
  protected array $controllerFiles = [];

  /**
   * ControllerParser constructor.
   *
   * @param array  $packages
   * @param string $extension
   * @throws ReflectionException
   */
  public function __construct(array $packages, string $extension = 'php')
  {
    parent::__construct();

    foreach ($packages as $package) {
      $this->controllerFiles = array_merge(
        $this->controllerFiles, FileUtils::scanFiles((string)$package, $extension)
      );
    }
  }

  /**
   * Parse Controller
   *
   * @return array
   * @throws ReflectionException
   */
  public function parse(): array
  {
    $container = [];

    foreach ($this->controllerFiles as $file) {
      if (!(is_file($file) && file_exists($file))) {
        continue;
      }

      $fileInfo = pathinfo($file);

      //暂时不考虑控制器包含名空间的情况
      /*$namespace = strtr(ucwords(strtr(substr(realpath($fileInfo['dirname']), strlen(APP_PATH . DIRECTORY_SEPARATOR)),
        ['\\' => ' ', '/' => ' '])), [' ' => '\\']);
      if (!(is_string($namespace) && $namespace)) {
        continue;
      }

      $class = '\\' . $namespace . '\\' . $fileInfo['filename'];*/

      $class = $fileInfo['filename'];
      if (!class_exists($class)) {
        continue;
      }

      $rf = RestContainer::getClassReflector($class);
      if (!$rf->isInstantiable()) {
        continue;
      }

      $controller = $this->reader->getClassAnnotation($rf, Controller::class);
      if (!($controller instanceof Controller)) {
        continue;
      }

      $stdClass = new stdClass();
      $stdClass->reflection = $rf;
      $stdClass->annotation = $controller;

      $container[] = $stdClass;
    }

    return $container;
  }
}